--[[
    邮储银行
]]
require("apm_core")
require("ApmJson")
require("extension")

local G_DEBUG = true

if G_DEBUG == false then
    function logDebug(fmt,...) end
    function logInfo(fmt,...) end
    function logWarn(fmt,...) end
    function logError(fmt,...) end
    function logFatal(fmt,...) end
end

local KRED='\x1B[0;31m'
local KSALMON='\x1B[1;31m'
local KGREEN='\x1B[0;32m'
local KLIMEGREEN='\x1B[1;32m'
local KYELLOW='\x1B[0;33m'
local KORANGE='\x1B[0;34m'
local KBLUE='\x1B[1;34m'
local KMAGENTA='\x1B[0;35m'
local KPINK='\x1B[1;35m'
local KCYAN='\x1B[0;36m'
local RESET='\x1B[0m'

--- main
function post_analysis()
    local ApmData = require("ApmData")
    if ApmData.getL7Proto() ~= 7222 then return end

    local s_data_name = ApmData.getField("tibcoems.properties.data_name", 1)
    if s_data_name ~= nil then
        s_data_name = string.trim(s_data_name)
        local _, _, v1, v2 = string.find(s_data_name, "^(%d+)_%d+_%d+_(%d+)_%d+$")
        local s_transtype, s_transtype_name
        if v1 == "0" then
            s_transtype_name = "单系统"
        elseif v1 == "1" then
            s_transtype_name = "跨系统"
        end

        if v2 == "01" then
            s_transtype_name = s_transtype_name .. "-负债账户"
        elseif v2 == "02" then
            s_transtype_name = s_transtype_name .. "-资产账户"
        elseif v2 == "03" then
            s_transtype_name = s_transtype_name .. "-负债账务"
        elseif v2 == "04" then
            s_transtype_name = s_transtype_name .. "-资产账务"
        elseif v2 == "05" then
            s_transtype_name = s_transtype_name .. "-现金凭证缴拨"
        elseif v2 == "18" then
            s_transtype_name = s_transtype_name .. "-会计流水"
        end

        local s_text = ApmData.getField("notify.tibcoems.text", 1)
        if s_text == nil then
            s_text = ApmData.getField("request.tibcoems.text", 1)
        end
        if s_text ~= nil then
            --            logInfo("_TEXT_:[%s]", s_text)
            local t_json_tree = ApmJson.decode(s_text)
            if t_json_tree ~= nil then
                -- 这里没有对应多个流水号的问题，只取了第一个
                local s_serial_no = t_json_tree[1].CLI_SERIAL_NO
                if s_serial_no ~= nil then
                    logInfo("CLI_SERIAL_NO:[%s]", s_serial_no)
                    ApmData.replaceField("transaction.code", s_serial_no)
                end
            end
        end

        if s_transtype_name ~= nil then
            s_transtype = v1 .. v2
            ApmData.replaceField("transaction.type_code", s_transtype)
            ApmData.replaceField("transaction.type_name", s_transtype_name)
            logInfo("(%s:%d->%s:%d) %s:%s",
                ApmData.getSrcIp(),
                ApmData.getSrcPort(),
                ApmData.getDstIp(),
                ApmData.getDstPort(),
                s_transtype,
                s_transtype_name
            )
        end
    end

    return
end
--v1.0.1
